package com.xc.controller;

import com.google.code.kaptcha.Producer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Collection;

@RestController
public class HelloController {

    @GetMapping("/hello")
    public String hello(Authentication authentication){
        String name = authentication.getName();
        Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
        for (GrantedAuthority authority : authorities) {
            System.out.println(authority.getAuthority());
        }
        return "hello "+name;
    }

    @PreAuthorize("hasAuthority('ROLE_admin')")
    @GetMapping("/admin")
    public String admin(Authentication authentication){
        String name = authentication.getName();
        Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
        for (GrantedAuthority authority : authorities) {
            System.out.println(authority.getAuthority());
        }
        return "admin "+name;
    }


    @RequestMapping({"/","/index"})
    public String index(){
        // 获取登录用户的用户名
        String name = SecurityContextHolder.getContext().getAuthentication().getName();
        return "index "+name;
    }


    @Autowired
    private Producer producer;

    @GetMapping("/vc.jpg")
    public void getVerifyCode(HttpServletResponse resp, HttpSession session) throws IOException {
        resp.setContentType("image/jpeg");

        String code = producer.createText();

        session.setAttribute("kaptcha",code);

        BufferedImage image = producer.createImage(code);

        try(ServletOutputStream out = resp.getOutputStream()) {
            ImageIO.write(image, "jpg", out);
        }

    }
}
